import Vue from 'vue'

function format(data) {
  return Vue.moment(data).format("YYYY-MM-DD");
}

function formatTimes(data) {
  const startDate = format(new Date(data.startDate * 1000));
  const endDate = format(new Date(data.endDate * 1000));
  const times = `${startDate} - ${endDate}`;
  return times
}

const state = {
  lists: []
}

const getters = {

}

const mutations = {
  GET_HOLIDAYMSG(state,res){
    state.lists = res.data.data.map(item => {
      const times = formatTimes(item)
      return {
        id: item.id,
        times: times,
        type: item.type === 0 ? "工作日" : "休息日",
        isHoliday: item.legal ? "是" : "否",
        remark: item.note
      };
    });
  },
  PUSH_HOLIDAYMSG(state,payload) {
    const times = formatTimes(payload)
    state.lists.push({
      id: payload.id,
      times,
      type: payload.type === 0 ? "工作日" : "休息日",
      isHoliday: payload.legal ? "是" : "否",
      remark: payload.note
    })
  },
  EDIT_HOLIDAYMSG(state,payload) {
    let index = state.lists.findIndex(val => {
      return val.id === payload.id
    })
    const times = formatTimes(payload)
    state.lists[index].id = payload.id
    state.lists[index].times = times
    state.lists[index].type = payload.type === 0 ? "工作日" : "休息日"
    state.lists[index].isHoliday = payload.legal ? "是" : "否"
    state.lists[index].remark = payload.note
  },
  DELETE_HOLIDAYMSG(state,payload) {
    if((typeof payload) == 'number') {
      let index = state.lists.findIndex(val => {
        return val.id == payload
      })
      state.lists.splice(index,1)
    } else{
      payload.forEach(item => {
        let index = state.lists.findIndex(val => {
          return val.id == item
        })
        state.lists.splice(index,1)
      })
    }
  }
}

const actions = {
  getHolidayMsg({commit, state}) { //获取数据
    return new Promise((resolve,reject) => {
      Vue.http.get("/holiday").then(res => {
        resolve(res)
      }).catch(err=>{
        console.log(err)
        reject(err)
      })
    })
  },
  addHoliday({commit,state},params) { //新增
    return new Promise((resolve,reject) => {
      Vue.http.post("/holiday",params).then(res=>{
        commit('PUSH_HOLIDAYMSG',res.data.data)
        resolve(res)
      }).catch(err=>{
        console.log(err)
        reject(err)
      })
    })
  },
  removeHoliday({commit, state},id) { //删除
    return new Promise((resolve,reject) => {
      Vue.http.delete(`/holiday/${id}`).then(res=>{
        resolve(res)
      }).catch(err=>{
        console.log(err)
        reject(err)
      })
    })
  },
  editHoliday({commit, state},params) { //修改
    return new Promise((resolve,reject) => {
      Vue.http.put(`/holiday/${params.id}`,params).then(res=>{
        resolve(res)
      }).catch(err=>{
        console.log(err)
        reject(err)
      })
    })
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}